/*
    The MIT License

    Copyright (c) 2010 IFMO/GameDev Studio

    Permission is hereby granted, free of charge, to any person obtaining a copy
    of this software and associated documentation files (the "Software"), to deal
    in the Software without restriction, including without limitation the rights
    to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
    copies of the Software, and to permit persons to whom the Software is
    furnished to do so, subject to the following conditions:

    The above copyright notice and this permission notice shall be included in
    all copies or substantial portions of the Software.

    THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
    IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
    FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
    AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
    LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
    OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
    THE SOFTWARE.
*/

#include "phys_local.h"

#include "BulletCollision/CollisionDispatch/btGhostObject.h"
#include "BulletDynamics/Character/btKinematicCharacterController.h"
#include "BulletDynamics/Character/btCharacterController2.h"

/*-----------------------------------------------------------------------------
	Phys character :
-----------------------------------------------------------------------------*/

#define STRVEC		"[%8.3f %8.3f %8.3f] "
#define XYZVEC(v)	(v).x(), (v).y(), (v).z()
btOverlappingPairCallback	*EPhysCharacter::overlap_pair_callback	=	NULL;

//
//	EPhysCharacter::InitGhostCallback
//
void EPhysCharacter::InitGhostCallback( btBroadphaseInterface *broadphase )
{
	SAFE_DELETE( overlap_pair_callback );
	overlap_pair_callback	=	new btGhostPairCallback();
	broadphase->getOverlappingPairCache()->setInternalGhostPairCallback( overlap_pair_callback );
}


//
//	EPhysCharacter::ShutdownGhostCallback
//
void EPhysCharacter::ShutdownGhostCallback( btBroadphaseInterface *broadphase )
{
	SAFE_DELETE( overlap_pair_callback );
	broadphase->getOverlappingPairCache()->setInternalGhostPairCallback( NULL );
}


//
//	EPhysCharacter::EPhysCharacter
//
EPhysCharacter::EPhysCharacter( EPhysics *phys, float height, float radius, float climbing_slope, float stair_step )
{
	this->phys = phys;
	
	this->world			=	phys->World();
	this->radius		=	radius;
	this->height		=	height;
	

	if (height<=0)			{ RUNTIME_ERROR("height <= 0"); }
	if (radius<=0)			{ RUNTIME_ERROR("radius <= 0"); }
	if (height>1000)		{ RUNTIME_ERROR("height > 1000"); }
	if (radius>1000)		{ RUNTIME_ERROR("radius > 1000"); }
	if (height<2*radius)	{ RUNTIME_ERROR("height < 2 * radius"); }
	
	btScalar characterHeight	=	height - 2*radius;
	btScalar characterWidth		=	radius;
	btScalar stepHeight			=	btScalar( stair_step );

	//	create ghost_shape :	
	ghost_shape					=	new btCapsuleShapeZ( characterWidth, characterHeight );

	//	create ghost object :
	btTransform startTransform;
	startTransform.setIdentity ();

	ghost_object = new btPairCachingGhostObject();
	ghost_object->setWorldTransform( startTransform );
	ghost_object->setCollisionShape( ghost_shape );
	ghost_object->setCollisionFlags( btCollisionObject::CF_CHARACTER_OBJECT );
	
	world->addCollisionObject( ghost_object, btBroadphaseProxy::AllFilter, btBroadphaseProxy::AllFilter );
	world->addAction( this );
	
	m_character	=	NULL;
	

	ResetTouches();	

	bool floor, ceil, walls;
	Move( EVector::kZero, floor, ceil, walls );
}


//
//	EPhysCharacter::ResetTouches
//
void EPhysCharacter::ResetTouches( void )
{
	touch.ceil	=	false;
	touch.floor	=	false;
	touch.walls	=	false;
}

//
//	EPhysCharacter::~EPhysCharacter
//
EPhysCharacter::~EPhysCharacter( void )
{
	world->removeAction( this );

	world->removeCollisionObject( ghost_object );
	SAFE_DELETE( ghost_object );

	SAFE_DELETE( ghost_shape );
}


//
//	EPhysCharacter::updateAction
//
void EPhysCharacter::updateAction( btCollisionWorld* collisionWorld, btScalar deltaTimeStep )
{
	if (m_character) {
		m_character->updateAction( collisionWorld, deltaTimeStep );
	} else {
	
		if (stored_move_dir.length()<0.00001f) {
			return;
		}
	
		PreStep( world );
		MoveForwardAndStrafe( world, stored_move_dir );

		stored_move_dir	=	btVector3(0,0,0);
	}
}


//
//	EPhysCharacter::Move
//
void EPhysCharacter::Move( const EVector &dir, bool &floor, bool &ceil, bool &walls )
{
	if (m_character) {
		m_character->setWalkDirection( ToVector( dir ) );
	} else {
		stored_move_dir	=	ToVector(dir);
	}
	
	floor	=	touch.floor;
	ceil	=	touch.ceil;
	walls	=	touch.walls;
}


//
//	EPhysCharacter::GetPose
//
void EPhysCharacter::GetPose( EPoint &position, EQuaternion &orient ) const
{
	btTransform xform;
	xform = ghost_object->getWorldTransform ();

	orient		= this->orient;
	position	= ToPoint( xform.getOrigin() - btVector3(0,0, height/2) );
}


//
//	EPhysCharacter::SetPose
//
void EPhysCharacter::SetPose( const EPoint &position, const EQuaternion &orient )
{
	this->orient	=	orient;
	
	btTransform	xform;
	xform.setIdentity();
	xform.setOrigin( ToPoint( position ) + btVector3(0,0, height/2) );
	
	ghost_object->setWorldTransform( xform );
}

/*-----------------------------------------------------------------------------
	Internal stuff (callbacks):
-----------------------------------------------------------------------------*/

//
//	ERayCastCB
//
class ERayCastCB : public btCollisionWorld::ClosestRayResultCallback {
	public:
							ERayCastCB		( btCollisionObject* self );
		virtual btScalar	addSingleResult	( btCollisionWorld::LocalRayResult& rayResult, bool normalInWorldSpace );
	protected:
		btCollisionObject* self;
	};


ERayCastCB::ERayCastCB( btCollisionObject* self )
 : btCollisionWorld::ClosestRayResultCallback(btVector3(0, 0, 0), btVector3(0, 0, 0))
{
	this->self = self;
}


btScalar ERayCastCB::addSingleResult( btCollisionWorld::LocalRayResult& rayResult, bool normalInWorldSpace )
{
	if (rayResult.m_collisionObject == self) {
		return 1.0;
	}

	return ClosestRayResultCallback::addSingleResult (rayResult, normalInWorldSpace);
}


//
//	EConvexCastCB
//	
class EConvexCastCB : public btCollisionWorld::ClosestConvexResultCallback {
	public:
							EConvexCastCB	( btCollisionObject* self, const btVector3 &dir, EPhysCharacter *character );
		virtual btScalar	addSingleResult	( btCollisionWorld::LocalConvexResult& convexResult, bool normalInWorldSpace );
	protected:
		EPhysCharacter		*character;
		btCollisionObject*	self;
		btVector3			dir;
	};


EConvexCastCB::EConvexCastCB( btCollisionObject* self, const btVector3 &dir, EPhysCharacter *character )
 : btCollisionWorld::ClosestConvexResultCallback(btVector3(0, 0, 0), btVector3(0, 0, 0))
{
	this->character	=	character;
	this->dir		=	dir.normalized();
	this->self		=	self;
}


btScalar EConvexCastCB::addSingleResult( btCollisionWorld::LocalConvexResult& convexResult,bool normalInWorldSpace )
{
	if (convexResult.m_hitCollisionObject == self) {
		return 1.0;
	}
	
	btTransform	transform		=	convexResult.m_hitCollisionObject->getWorldTransform();
	btVector3	world_normal	=	convexResult.m_hitNormalLocal;
	
	if (!normalInWorldSpace) {
		world_normal	=	world_normal * transform.getBasis();
		world_normal.normalize();
	}
		
	if (world_normal.z() > 0.707) {
		character->touch.floor	=	true;
	} else 
	if (world_normal.z() < -0.707) {
		character->touch.ceil	=	true;
	} else {
		character->touch.walls	=	true;
	}
	
	if ( abs( world_normal.dot( dir ) ) < 0.1f ) {
		return 1.0f;
	}

	//rs()->GetDVScene()->DrawArrow( ToVec4( m_hitPointWorld ), ToVec4( world_normal ), 10, EVec4(1,0,1,1) );

	return ClosestConvexResultCallback::addSingleResult (convexResult, normalInWorldSpace);
}


/*-----------------------------------------------------------------------------
	Internal stuff (moving):
-----------------------------------------------------------------------------*/

static void LogVector( const char *what, const btVector3 &v )
{
	LOGF("%-8s = [ %8.3f  %8.3f  %8.3f]", what, v.x(), v.y(), v.z());
}

static void DebugVector( const char *what, const btVector3 &v )
{
	DEBUG_STRING("%-8s = [ %8.3f  %8.3f  %8.3f]", what, v.x(), v.y(), v.z());
}



//
//	EPhysCharacter::PreStep
//
void EPhysCharacter::PreStep( btCollisionWorld *world )
{
	int num_penetration_loops = 0;
	touching_contact = false;
	
	ResetTouches();	

	while ( RecoverFromPenetration2(world) ) {
		num_penetration_loops++;
		touching_contact = true;
		if (num_penetration_loops > 4) {
			break;
		}
	}
}

//
//	EPhysCharacter::MoveForwardAndStrafe
//
void EPhysCharacter::MoveForwardAndStrafe( btCollisionWorld *world, const btVector3 &move_dir )
{
	btVector3	normal_dir	=	move_dir.normalized();
	btVector3	start;

	MoveToObject	move_to_obj;
	
	move_to_obj.reached		=	false;
	move_to_obj.fraction	=	0;
	move_to_obj.new_origin	=	ghost_object->getWorldTransform().getOrigin();
	move_to_obj.next_move	=	move_dir;
	
	//DEBUG_STRING("--------");
	//DEBUG_STRING("Walk dir: "STRVEC, XYZVEC(move_dir));
	
	for (uint i=0; i<10; i++) {

		//DEBUG_STRING("%02d : Frac = %8.3f, Next: "STRVEC, 
		//	i, move_to_obj.fraction, XYZVEC(move_to_obj.next_move));
		
		btVector3	from	=	move_to_obj.new_origin;
		btVector3	to		=	from + move_to_obj.next_move;

		//LOGF("reached = %s", move_to_obj.reached ? "true" : "false");
		
		MoveToClosestObject( world, from, to, move_to_obj );
		
		if (!move_to_obj.reached) {
			break;
		}

		if (normal_dir.dot( move_to_obj.next_move ) < 0) {
			break;
		}
	}
	
	btTransform	new_xform;
	new_xform.setIdentity();
	new_xform.setOrigin( move_to_obj.new_origin );
	
	ghost_object->setWorldTransform( new_xform );
}


//
//	ReflectionDirection 
//
btVector3 ReflectionDirection (const btVector3& direction, const btVector3& normal)
{
	return direction - (btScalar(2.0) * direction.dot(normal)) * normal;
}

//
//	NormalComponent 
//
static btVector3 NormalComponent(const btVector3& direction, const btVector3& normal)
{
	btScalar magnitude = direction.dot(normal.normalized());
	return normal * magnitude;
}


//
//	TangentialComponent
//
static btVector3 TangentialComponent (const btVector3& direction, const btVector3& normal)
{
	return direction - NormalComponent(direction, normal);
}




//
//	EPhysCharacter::MoveToClosestObject
//
void EPhysCharacter::MoveToClosestObject( btCollisionWorld *world, const btVector3 &from_point, const btVector3 &to_point, MoveToObject &move_to_obj )
{
	btVector3	move_dir	=	to_point - from_point;
	
	btTransform	from;
	btTransform	to;
	
	from.setIdentity();
	to.setIdentity();
	
	from.setOrigin( from_point );
	to.setOrigin( to_point );

	EConvexCastCB	callback( ghost_object, to_point - from_point, this );

	//	trace ghost_shape through the world :	
	float	margin	=	ghost_shape->getMargin();
	ghost_shape->setMargin( margin + 0.001f );

	float allowed_ccd_penetration = world->getDispatchInfo().m_allowedCcdPenetration;


	//
	//	perform convex sweep test :
	//	
	//world->convexSweepTest( ghost_shape, from, to, callback, allowed_ccd_penetration );
	ghost_object->convexSweepTest( ghost_shape, from, to, callback, 0 );

	if ( callback.hasHit() ) {
	
		//	we hit some object - move along tangential component:	
		float fraction			=	callback.m_closestHitFraction;
		
		btVector3 stop_point	=	from_point + (move_dir * fraction);
		btVector3 normal		=	callback.m_hitNormalWorld;
		
		//rs()->GetDVScene()->DrawPoint( ToPoint( stop_point ), 0.1, EVec4(1,0.5,0.5,1) );
		
		move_to_obj.fraction	=	fraction;
		move_to_obj.reached		=	true;
		move_to_obj.next_move	=	TangentialComponent( to_point - stop_point, normal );		
		move_to_obj.new_origin	=	stop_point;
		
	} else {
	
		//	we didn't hit any object, just stop moving :
		move_to_obj.reached		=	false;
		move_to_obj.next_move	=	btVector3(0,0,0);		
		move_to_obj.new_origin	=	to_point;
	}

	ghost_shape->setMargin( margin );
}


//
//	EPhysCharacter::RecoverFromPenetration2
//
bool EPhysCharacter::RecoverFromPenetration2( btCollisionWorld *world )
{
	return RecoverFromPenetration( world );
}


//
//	EPhysCharacter::RecoverFromPenetration
//
bool EPhysCharacter::RecoverFromPenetration( btCollisionWorld *world )
{
	bool penetration = false;
	
	touch.ceil	=	false;
	touch.floor	=	false;
	touch.walls	=	false;

	world->getDispatcher()->dispatchAllCollisionPairs(ghost_object->getOverlappingPairCache(), world->getDispatchInfo(), world->getDispatcher());

	//	get current position :
	btVector3	current_position = ghost_object->getWorldTransform().getOrigin();

	//	dispatch all overlapping pairs :	
	btScalar maxPen = btScalar(0.0);
	
	//	over all pairs :
	for (int i = 0; i < ghost_object->getOverlappingPairCache()->getNumOverlappingPairs(); i++) {
	
		manifold_array.resize(0);

		btBroadphasePair* collisionPair = &ghost_object->getOverlappingPairCache()->getOverlappingPairArray()[i];

		//	check algorithms :		
		if (collisionPair->m_algorithm) {
			collisionPair->m_algorithm->getAllContactManifolds(manifold_array);
		}

		//	iterate over manifold's array :
		for (int j=0;j<manifold_array.size();j++) {
		
			btPersistentManifold* manifold = manifold_array[j];
			
			btScalar directionSign = manifold->getBody0() == ghost_object ? btScalar(-1.0) : btScalar(1.0);
			
			for (int p=0; p<manifold->getNumContacts(); p++) {
				const btManifoldPoint	&pt = manifold->getContactPoint(p);

				////	DHG : 				
				//btVector3 touch_pos = 0.5 * (pt.getPositionWorldOnA() + pt.getPositionWorldOnB());
				//rs()->GetDVScene()->DrawPoint( ToPoint( touch_pos ), 0.1, EVec4(1,0.0,0.0,1) );

				if (pt.getDistance() < 0.0)	{
					if (pt.getDistance() < maxPen) {
						maxPen = pt.getDistance();
						touching_normal = pt.m_normalWorldOnB * directionSign;//??

						//	classify touching vectors :
						touching_normal.normalize();
						
					}
					current_position += pt.m_normalWorldOnB * directionSign * pt.getDistance() * btScalar(0.2);
					penetration = true;
				} else {
					//printf("touching %f\n", pt.getDistance());
				}
			}
			
			//manifold->clearManifold();
		}
	}

	//	set new position :	
	btTransform newTrans = ghost_object->getWorldTransform();
	newTrans.setOrigin(current_position);
	ghost_object->setWorldTransform(newTrans);
	
//	printf("m_touchingNormal = %f,%f,%f\n",m_touchingNormal[0],m_touchingNormal[1],m_touchingNormal[2]);
	return penetration;
}
